package com.example.bm.common.util;


import com.example.bm.system.pojo.MenuFormSelect;
import com.example.bm.system.pojo.MenuTree;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author bryceM
 */
@NoArgsConstructor
public class MenuTreeUtil {

    /**
     * 构建菜单
     *
     * @param nodes
     * @param <T>
     * @return
     */
    public static <T> List<MenuTree<T>> buildMenuTree(List<MenuTree<T>> nodes) {
        if (nodes == null) {
            return null;
        }
        //顶级节点
        List<MenuTree<T>> topNodes = new ArrayList<>();
        nodes.forEach(children -> {
            String pid = children.getParentId();
            if (pid == null || "0".equals(pid)) {
                //一级节点
                topNodes.add(children);
                return;
            }
            //遍历父节点
            for (MenuTree<T> parent : nodes) {
                String id = parent.getId();
                if (id != null && id.equals(pid)) {
                    parent.getChildren().add(children);
                    children.setHasParent(true);
                    parent.setHasChild(true);
                    return;
                }
            }
        });
        return topNodes;
    }

    /**
     * formSelect 组件数据形式
     * @param nodes
     * @param <T>
     * @return
     */
    public static <T> List<MenuFormSelect<T>> buildFormSelectMenuTree(List<MenuFormSelect<T>> nodes) {
        if (nodes == null) {
            return null;
        }
        List<MenuFormSelect<T>> topNodes = new ArrayList<>();
        nodes.forEach(children -> {
            String pid = children.getParentId();
            if (pid == null || "0".equals(pid)) {
                topNodes.add(children);
                return;
            }
            for (MenuFormSelect<T> parent : nodes) {
                String id = parent.getId();
                if (id != null && id.equals(pid)) {
                    parent.getChildren().add(children);
                    parent.setHasChild(true);
                    return;
                }
            }
        });
        return topNodes;
    }

}